<template>
  <div id="Login">
    Login
  </div>

  <el-input v-model="username" placeholder="Input Your Account" :clearable=true maxlength="20" size="large"
    :prefix-icon="User" class="BOX_input"></el-input>

  <el-input v-model="password" placeholder="Input Your Password" type="password" :show-password=true size="large"
    :prefix-icon="Lock" class="BOX_input" @keydown="handleKeyCode($event)"></el-input>

  <div id="cutLine"></div>

  <el-button type="primary" class="BOX_button" :loading="loginLoading" @click="click">Login</el-button>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { Login } from "../api/api";
import { User, Lock } from "@element-plus/icons-vue"

const username = ref("");
const password = ref("");
const router = useRouter();
const loginLoading = ref(false);

async function click() {
  // 输入检测
  if (username.value == "") {
    ElMessage.error("Please input your ACCOUNT");
    return;
  } else if (password.value == "") {
    ElMessage.error("Please input your PASSWORD");
    return;
  }

  // 登录
  loginLoading.value = true;
  const responseCode = await Login(username.value, password.value);
  // console.log(document.cookie);
  // 无用户
  if (responseCode == 0) {
    loginLoading.value = false;
    ElMessage.error("access denied");
    return;
  }
  // 密码错误
  else if (responseCode == 2) {
    loginLoading.value = false;
    ElMessage.error("wrong password");
    return;
  }
  
  // 成功登录
  else if (responseCode == 1) {
    // 检测路由是否跳转成功
    const navigationResult = await router.push("/");
    loginLoading.value = false;
    if (navigationResult) {
      ElMessage.error("You are NOT ALLOW to use BitGPT");
    } else {
      ElMessage.success("Welcome to use BitGPT");
    }
  }
}

function handleKeyCode(event) {
  if (event.keyCode == 13) {
    click();
  }
}
</script>

<style scoped>
#Login {
  width: 80%;
  font-weight: 1000;
  font-size: large;
  color: white;
}

#cutLine {
  width: 90%;
  height: 1px;
  background-color: gray;
  top: 10px;
}

.BOX_input {
  width: 80%;
  margin: 10px;
}

.BOX_button {
  width: 80%;
  margin: 40px;
}
</style>